package week9;

import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;

public class IO_Operate {
    public static void main(String[] args) throws IOException {

        try{

        File file = new File("E:\\mypro", "sort.txt");

        System.out.print("输入数字: ");
        Scanner scan = new Scanner(System.in);
        String string = scan.nextLine();

        Writer writer = new FileWriter(file);
        writer.write(string);
        writer.flush();

        Reader reader = new FileReader(file);//读取
        String str = "";
        char[] chars = new char[10];
        int length =reader.read(chars);
        for (int d = 0; d < chars.length; d++) {
            str += chars[d];
        }

        System.out.println("输入的是:" + str);
        reader.close();

        StringTokenizer st1 = new StringTokenizer(str, " ", false);//分隔

        int n = 0;
        int[] ints = new int[st1.countTokens()];//转为int数组
        while (st1.hasMoreTokens()) {
            ints[n] = Integer.valueOf(st1.nextToken());
            n++;
        }

        System.out.print("读取的是: ");
        for (int b = 0; b < ints.length; b++) {
            System.out.print(ints[b] + " ");
        }
        System.out.println();

        str = "";
        InsertionSort(ints);// 排序并转为String数组
        System.out.print("排序后: ");
        for (int c = 0; c < ints.length; c++) {
            System.out.print(ints[c] + " ");
            str += ints[c] + " ";
        }
        System.out.println();

        writer.write("排序后: ");//写入
        writer.write(str);
        writer.flush();

    }catch (FileNotFoundException e){
            System.out.println("系统找不到指定路径.");
        }
    }


    private static void InsertionSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int temp = arr[i];
            int j = i - 1;
            while (j >= 0 && temp < arr[j]) {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = temp;
        }
    }
}
